package com.ttl.bc.ap.invoice.bo;

import hibernate.util.HibernateUtil;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.ttl.bc.ap.ap.bean.BCAPBean;

import com.ttl.bc.ap.ap.db.BCAPDAO;

import com.ttl.bc.ap.invoice.action.BCAPInvoice2Form;
import com.ttl.bc.ap.invoice.action.BCAPInvoiceForm;
import com.ttl.bc.ap.invoice.action.InvFindForm;
import com.ttl.bc.ap.invoice.action.POFindForm;
import com.ttl.bc.ap.invoice.action.PRFindForm;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceBean;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceSubBean;
import com.ttl.bc.ap.invoice.bean.BCAPInvoiceSubShowBean;
import com.ttl.bc.ap.invoice.bean.ITTL_P2;
import com.ttl.bc.ap.paymoney.bean.BCPayMoneyBean;
import com.ttl.bc.ap.paymoney.db.BCPayMoneyBO;
import com.ttl.bc.ap.paymoney.db.BCPayMoneyDAO;

import com.ttl.bc.ap.purchaseorder.bean.BCPurchaseOrderBean;
import com.ttl.bc.ap.purchaseorder.bean.BCPurchaseOrderShowBean;
import com.ttl.bc.ap.purchaseorder.bean.BCPurchaseOrderSubBean;
import com.ttl.bc.ap.purchaseorder.bean.BCPurchaseOrderSubShowBean;
import com.ttl.bc.ap.purchaseorder.db.BCPurchaseOrderDAO;

import com.ttl.bc.ap.stkrequest.BCStkRequestBean;
import com.ttl.bc.ap.stkrequest.BCStkRequestDAO;
import com.ttl.bc.ap.stkrequest.BCStkRequestSubBean;


import com.ttl.bc.ar.reqconfirm.bean.BCReqConfirmBean;
import com.ttl.bc.ar.reqconfirm.bean.BCReqConfirmSubBean;

import com.ttl.bc.processstock.bean.ProcessStockBean;
import com.ttl.bc.processstock.db.ProcessStockDAO;
import com.ttl.bc.vat.apwtaxlist.bean.BCAPWTaxListBean;
import com.ttl.bc.vat.apwtaxlist.db.BCAPWTaxListBO;
import com.ttl.bc.vat.apwtaxlist.db.BCAPWTaxListDAO;
import com.ttl.bc.vat.inputtax.bean.BCInputTaxBean;
import com.ttl.bc.vat.inputtax.db.BCInputTaxBO;
import com.ttl.bc.vat.inputtax.db.BCInputTaxDAO;
import com.ttl.common.util.CommonUtils;
import com.ttl.common.util.Page;

public class BCAPInvoiceBO {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ArrayList findOLD(ActionForm form, HttpServletRequest request) {
		
//		BCAPInvoiceForm invForm =(BCAPInvoiceForm)form;
//				
//		String hql = "FROM BCReqConfirmBean s  " +
//					 "WHERE  " +
//					 " s.docNo in ( '"+invForm.getDocNo1()+"', "+
//					 " '"+invForm.getDocNo2()+"', "+
//					 " '"+invForm.getDocNo3()+"', "+
//					 " '"+invForm.getDocNo4()+"', "+
//					 " '"+invForm.getDocNo5()+"') and "+
//					 " s.ittl_status not in ('2','3') ";								
		
		BCAPInvoice2Form invForm =(BCAPInvoice2Form)form;
		String docNo = "";
		for(int i=0; i<invForm.getDocNoArray().length; i++) {
			docNo = docNo +"'"+ invForm.getDocNoArray()[i] + "',";
		}
		if(docNo.length()>0) {
			docNo = docNo.substring(0, docNo.length()-1);
		}
		
		String hql = "FROM BCReqConfirmBean s  " +
		 "WHERE  " +
		 " s.docNo in ( "+docNo+" ) and "+
		 " s.ittl_status not in ('2','3') ";		
		
		System.out.println(hql);
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		ArrayList results = (ArrayList)dao.find(hql);
				
		ArrayList al = new ArrayList();
		if(results !=null && results.size()>0) {
			
			for(int i=0; i<results.size(); i++) {
				BCReqConfirmBean f = (BCReqConfirmBean)results.get(i);
				
		    	Iterator it = f.getBcReqConfirmSubs().iterator();
		    	
		        while(it.hasNext()) {
		        	BCReqConfirmSubBean sub = (BCReqConfirmSubBean)it.next();
		        	
		        	BCPurchaseOrderShowBean bean = new BCPurchaseOrderShowBean();
		        	bean.setItemCode(sub.getItemCode());
		        	bean.setItemName(sub.getItemName());
		        	
		        	hql = "FROM BCStkRequestBean WHERE docNo='"+f.getDocNo()+"'";
		        	BCStkRequestDAO dao2 = new BCStkRequestDAO();
		        	ArrayList al2 = (ArrayList)dao2.find(hql);
		        	
		        	for(int j=0; j<al2.size(); j++) {		        		
		        		BCStkRequestBean stk = (BCStkRequestBean)al2.get(j);
		        		bean.setProjectCode(stk.getProjectCode());
		        		
				    	Iterator it2 = stk.getBcStkRequestSubs().iterator();
				    	@SuppressWarnings("unused")
						int x =0;
				        while(it2.hasNext()) {
				        	BCStkRequestSubBean sub2 = (BCStkRequestSubBean)it2.next();
				        	if(sub2.getItemCode().equals(sub.getItemCode()) && 
				        			sub2.getItemName().equals(sub.getItemName() )) {
				        		bean.setUnitName(sub2.getIttl_unitName());
				        	}				        	
				        }
		        	}
						
		        	bean.setUnitCode(sub.getUnitCode());
		        	bean.setQty(""+sub.getQty());
		        	bean.setStkReqNo(sub.getStkRequestNo());	
		        	bean.setConfirmNo(f.getDocNo());
		        	bean.setDepartCode(sub.getDepartCode());
		        	
		        	al.add(bean);		        		
		        }
			}
		}				
		return al;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ArrayList find(ActionForm form, HttpServletRequest request) {
											
		//BCAPInvoice2Form invForm =(BCAPInvoice2Form)form;
		PRFindForm invForm =(PRFindForm)form;
		String docNo = "";
		for(int i=0; i<invForm.getDocNoArray().length; i++) {
			docNo = docNo +"'"+ invForm.getDocNoArray()[i] + "',";
		}
		if(docNo.length()>0) {
			docNo = docNo.substring(0, docNo.length()-1);
		}
		
		String hql = "FROM BCReqConfirmBean s  " +
		 "WHERE  " +
		 " s.docNo in ( "+docNo+" ) and "+
		 " s.ittl_status not in ('2','3') ";		
		
		System.out.println(hql);
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		ArrayList results = (ArrayList)dao.find(hql);
				
		ArrayList al = new ArrayList();
		if(results !=null && results.size()>0) {
			
			int id=0;
			for(int i=0; i<results.size(); i++) {
				BCReqConfirmBean f = (BCReqConfirmBean)results.get(i);
				
		    	Iterator it = f.getBcReqConfirmSubs().iterator();
		    	
		        while(it.hasNext()) {
		        	BCReqConfirmSubBean sub = (BCReqConfirmSubBean)it.next();
		        	
		        	BCPurchaseOrderShowBean bean = new BCPurchaseOrderShowBean();
		        	
		        	bean.setLineNumber(""+(++id));
		        	bean.setItemCode(sub.getItemCode());
		        	bean.setItemName(sub.getItemName());
		        	bean.setUnitCode(sub.getUnitCode());
		        	bean.setQty(""+sub.getQty());		        	
		        	bean.setIttl_purchaseCode(sub.getStkRequestNo());
		        	bean.setStkReqNo(sub.getStkRequestNo());		        	
		        	bean.setConfirmNo(f.getDocNo());
		        			        			        	
		        	bean.setDepartCode(sub.getDepartCode());
		        	
		        	hql = "FROM BCStkRequestBean WHERE docNo='"+f.getDocNo()+"'";
		        	BCStkRequestDAO dao2 = new BCStkRequestDAO();
		        	ArrayList al2 = (ArrayList)dao2.find(hql);
		        	
		        	for(int j=0; j<al2.size(); j++) {		        		
		        		BCStkRequestBean stk = (BCStkRequestBean)al2.get(j);
		        		bean.setProjectCode(stk.getProjectCode());
		        		
				    	Iterator it2 = stk.getBcStkRequestSubs().iterator();
				    	@SuppressWarnings("unused")
						int x =0;
				        while(it2.hasNext()) {
				        	BCStkRequestSubBean sub2 = (BCStkRequestSubBean)it2.next();
				        	
				        	bean.setWhCode("10");
				        	bean.setShelfCode("10");
				        	
				        	bean.setLineItem_whCode("10");
				        	bean.setLineItem_shelfCode("10");
				        	bean.setLineItem_statusReceive("0");
				        	bean.setLineItem_departCode(sub.getDepartCode());				        	
				        	bean.setLineItem_projectCode(sub2.getProjectCode());
				        					        	
				        	if(sub2.getItemCode().equals(sub.getItemCode()) && 
				        			sub2.getItemName().equals(sub.getItemName() )) {
				        		bean.setUnitName(sub2.getIttl_unitName());
				        	}				        	
				        }
		        	}
							        			        	
		        	request.setAttribute("departCode", bean.getDepartCode());
		        	request.setAttribute("projectCode", bean.getProjectCode());
		        	al.add(bean);		        		
		        }
			}
		}				
		return al;
	}	

	@SuppressWarnings("rawtypes")
	public Object getBCAPInvoiceForm(ArrayList results) {
		BCAPInvoiceForm form = new BCAPInvoiceForm();
		
		for(int i=0; i<results.size(); i++) {
			BCPurchaseOrderShowBean bean = (BCPurchaseOrderShowBean)results.get(i);
			
			form.setProjectCode(bean.getProjectCode());
			form.setDepartCode(bean.getDepartCode());
			switch (i+1) {
			case 1:
					form.setItemCode1(bean.getItemCode());
					form.setItemName1(bean.getItemName());
					form.setUnitCode1(bean.getUnitCode());	
					form.setUnitName1(bean.getUnitName());
				
					form.setStkReqNo1(bean.getStkReqNo());
					form.setConfirmNo1(bean.getConfirmNo());
					
					break;
			case 2:
				form.setItemCode2(bean.getItemCode());
				form.setItemName2(bean.getItemName());
				form.setUnitCode2(bean.getUnitCode());
				form.setUnitName2(bean.getUnitName());
				
				form.setStkReqNo2(bean.getStkReqNo());
				form.setConfirmNo2(bean.getConfirmNo());								
				break;
			case 3:
				form.setItemCode3(bean.getItemCode());
				form.setItemName3(bean.getItemName());
				form.setUnitCode3(bean.getUnitCode());
				form.setUnitName3(bean.getUnitName());
				
				form.setStkReqNo3(bean.getStkReqNo());
				form.setConfirmNo3(bean.getConfirmNo());								
				break;
			case 4:
				form.setItemCode4(bean.getItemCode());
				form.setItemName4(bean.getItemName());
				form.setUnitCode4(bean.getUnitCode());
				form.setUnitName4(bean.getUnitName());
				
				form.setStkReqNo4(bean.getStkReqNo());
				form.setConfirmNo4(bean.getConfirmNo());								
				break;
			case 5:
				form.setItemCode5(bean.getItemCode());
				form.setItemName5(bean.getItemName());
				form.setUnitCode5(bean.getUnitCode());
				form.setUnitName5(bean.getUnitName());
				
				form.setStkReqNo5(bean.getStkReqNo());
				form.setConfirmNo5(bean.getConfirmNo());								
				break;
			case 6:
				form.setItemCode6(bean.getItemCode());
				form.setItemName6(bean.getItemName());
				form.setUnitCode6(bean.getUnitCode());
				form.setUnitName6(bean.getUnitName());
				
				form.setStkReqNo6(bean.getStkReqNo());
				form.setConfirmNo6(bean.getConfirmNo());								
				break;
			case 7:
				form.setItemCode7(bean.getItemCode());
				form.setItemName7(bean.getItemName());
				form.setUnitCode7(bean.getUnitCode());
				form.setUnitName7(bean.getUnitName());
				
				form.setStkReqNo7(bean.getStkReqNo());
				form.setConfirmNo7(bean.getConfirmNo());								
				break;
			case 8:
				form.setItemCode8(bean.getItemCode());
				form.setItemName8(bean.getItemName());
				form.setUnitCode8(bean.getUnitCode());
				form.setUnitName8(bean.getUnitName());
				
				form.setStkReqNo8(bean.getStkReqNo());
				form.setConfirmNo8(bean.getConfirmNo());								
				break;
			case 9:
				form.setItemCode9(bean.getItemCode());
				form.setItemName9(bean.getItemName());
				form.setUnitCode9(bean.getUnitCode());
				form.setUnitName9(bean.getUnitName());
				
				form.setStkReqNo9(bean.getStkReqNo());
				form.setConfirmNo9(bean.getConfirmNo());								
				break;
			case 10:
				form.setItemCode10(bean.getItemCode());
				form.setItemName10(bean.getItemName());
				form.setUnitCode10(bean.getUnitCode());
				form.setUnitName10(bean.getUnitName());
				
				form.setStkReqNo10(bean.getStkReqNo());
				form.setConfirmNo10(bean.getConfirmNo());								
				break;
			case 11:
				form.setItemCode11(bean.getItemCode());
				form.setItemName11(bean.getItemName());
				form.setUnitCode11(bean.getUnitCode());
				form.setUnitName11(bean.getUnitName());
				
				form.setStkReqNo11(bean.getStkReqNo());
				form.setConfirmNo11(bean.getConfirmNo());								
				break;
			case 12:
				form.setItemCode12(bean.getItemCode());
				form.setItemName12(bean.getItemName());
				form.setUnitCode12(bean.getUnitCode());
				form.setUnitName12(bean.getUnitName());
				
				form.setStkReqNo12(bean.getStkReqNo());
				form.setConfirmNo12(bean.getConfirmNo());								
				break;
			case 13:
				form.setItemCode13(bean.getItemCode());
				form.setItemName13(bean.getItemName());
				form.setUnitCode13(bean.getUnitCode());
				form.setUnitName13(bean.getUnitName());
				
				form.setStkReqNo13(bean.getStkReqNo());
				form.setConfirmNo13(bean.getConfirmNo());								
				break;
			case 14:
				form.setItemCode14(bean.getItemCode());
				form.setItemName14(bean.getItemName());
				form.setUnitCode14(bean.getUnitCode());
				form.setUnitName14(bean.getUnitName());
				
				form.setStkReqNo14(bean.getStkReqNo());
				form.setConfirmNo14(bean.getConfirmNo());								
				break;
			case 15:
				form.setItemCode15(bean.getItemCode());
				form.setItemName15(bean.getItemName());
				form.setUnitCode15(bean.getUnitCode());
				form.setUnitName15(bean.getUnitName());
				
				form.setStkReqNo15(bean.getStkReqNo());
				form.setConfirmNo15(bean.getConfirmNo());								
				break;
			case 16:
				form.setItemCode16(bean.getItemCode());
				form.setItemName16(bean.getItemName());
				form.setUnitCode16(bean.getUnitCode());
				form.setUnitName16(bean.getUnitName());
				
				form.setStkReqNo16(bean.getStkReqNo());
				form.setConfirmNo16(bean.getConfirmNo());								
				break;
			case 17:
				form.setItemCode17(bean.getItemCode());
				form.setItemName17(bean.getItemName());
				form.setUnitCode17(bean.getUnitCode());
				form.setUnitName17(bean.getUnitName());
				
				form.setStkReqNo17(bean.getStkReqNo());
				form.setConfirmNo17(bean.getConfirmNo());								
				break;
			case 18:
				form.setItemCode18(bean.getItemCode());
				form.setItemName18(bean.getItemName());
				form.setUnitCode18(bean.getUnitCode());
				form.setUnitName18(bean.getUnitName());
				
				form.setStkReqNo18(bean.getStkReqNo());
				form.setConfirmNo18(bean.getConfirmNo());								
				break;
			case 19:
				form.setItemCode19(bean.getItemCode());
				form.setItemName19(bean.getItemName());
				form.setUnitCode19(bean.getUnitCode());
				form.setUnitName19(bean.getUnitName());
				
				form.setStkReqNo19(bean.getStkReqNo());
				form.setConfirmNo19(bean.getConfirmNo());								
				break;
			case 20:
				form.setItemCode20(bean.getItemCode());
				form.setItemName20(bean.getItemName());
				form.setUnitCode20(bean.getUnitCode());
				form.setUnitName20(bean.getUnitName());
				
				form.setStkReqNo20(bean.getStkReqNo());
				form.setConfirmNo20(bean.getConfirmNo());								
				break;				
			default:
				break;
			}
			
		}
		
		return form;
	}

	public boolean addInvoice(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		
		return new BCAPInvoiceDAO().addInvoice(form);
	}
	
	@SuppressWarnings("rawtypes")
	public boolean add(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		
		BCAPInvoiceBean  inv = (BCAPInvoiceBean)BCAPInvoiceBO.getObject(form);
		
		//request.setAttribute("docNoFind", inv.getDocNo());
				
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceDAO #mode :add");		
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		String hql = "FROM BCAPInvoiceBean WHERE docNo = '"+inv.getDocNo()+"' ";
		List al = dao.find(hql);
		if(al!=null && al.size()>0) {
			String maxDocNo = CommonUtils.getMaxBCAPInvoiceDocNo(inv.getDocNo());
			inv.setDocNo(maxDocNo);			
		}	
		
		if(inv.getDocNo().substring(0, 3).equalsIgnoreCase("BCS")) {
			//บันทึกเงินสดย่อย
			BCPayMoneyBean pay = (BCPayMoneyBean)BCPayMoneyBO.getObject(form);			
			BCPayMoneyDAO dao4 = new BCPayMoneyDAO();
			dao4.add(pay);
			
			// ถ้ามูลค่าสุทธิ < ยอดรวมสินค้า   ->ถือเป็นหัก ณ ที่จ่าย			
			if(inv.getNetDebtAmount().doubleValue()<inv.getTotalAmount().doubleValue()) {
				BCAPWTaxListBean wTax = (BCAPWTaxListBean)BCAPWTaxListBO.getObject(form);
				BCAPWTaxListDAO dao6 = new BCAPWTaxListDAO();
				dao6.add(wTax);
				
				inv.setSumOfWTax(wTax.getwTaxAmount());
			}			
		}else if(inv.getDocNo().substring(0, 3).equalsIgnoreCase("CRS") ||
					inv.getDocNo().substring(0, 3).equalsIgnoreCase("CMD")) {				
				BCAPDAO apDao = new BCAPDAO();
				apDao.updateDebtAmount(inv);
				System.out.println("update :DebtAmount"); 
		}
		
		// ถ้ามีเลขที่ใบกำกับภาษี (taxNo) ให้เพิ่มใน BCInputTax 		
		if(inv.getTaxNo()!=null && !inv.getTaxNo().equals("")) {
			BCInputTaxBean tax = (BCInputTaxBean)BCInputTaxBO.getObject(form);
			BCInputTaxDAO dao5 = new BCInputTaxDAO();
			dao5.add(tax);
		}		
		dao.add(inv);
		
		dao.addITTL_P2(inv);
		
		// ใส่ข้อมูล itemCode รายการนั้นใน table: processStock 
		ProcessStockDAO p = new ProcessStockDAO();
		String[] item_of_service = {"A-01", "A-02", "C-3",  "C-03",  "D-03", "D-04", "D-4",  "E-04", "E-05", "E-4",  "E-5",  "E-S-E","EXPORT",
									"F-04", "F-05", "F-06", "F-4",  "F-5",  "F-6",  "G-06", "G-08", "G-10", "G-11", "G-12", 
									"G-13", "G-14", "G-24", "GE",   "H-07", "H-08", "H-15", "HO",   "I-10", "I-16", "IM",
									"INT",  "J-11", "J-17", "K-14", "K-15", "K-16", "K-17", "K-18", "L-18", "L-19", "M-19",
									"M-21", "N-20", "N-22", "O-21", "P-22", "P-23", "Q-23", "R-24", "R-25", "S-25", "SE", "TREEX", "TRECO", 
									"SER-006","SES","ST",   "T-26", "U-27", "V-28", "Z-01", "Z-02", "Z-03", "Z-04", "Z-05", "Z-06"};
		
		
		
		
		
		Iterator it = inv.getBcAPInvoiceSubs().iterator();
		
		while(it.hasNext()) {
			BCAPInvoiceSubBean sub = (BCAPInvoiceSubBean)it.next();
									
			BCStkRequestDAO dao2 = new BCStkRequestDAO();
			//dao2.updateStatus(sub.getPoRefNo());
			
			//update ว่าใบ พ.1 ขอซื้อนั้น ใช้บันทึกซื้อแล้ว (แม้ไม่ได้ซึ้อทุก item )
			dao2.updateStatus(sub.getStkReqNo(),"2"); //0=รอเบิก, 1=รอซื้อสร้าง po แล้ว, 2=ซื้อแล้ว, 3=จ่ายแล้ว, 4=ยืนยันรับของ
			//update item ที่ซื้อเข้ามาตาม rowOrder
			dao2.updateStatusAfterCreateInvoice(form,"2");
			
//			BCReqConfirmDAO dao3 = new BCReqConfirmDAO();
//			//dao3.updateStatus(sub.getPoRefNo());
//			dao3.updateStatus(sub.getStkReqNo(),"2");
			
			BCPurchaseOrderDAO dao4 = new BCPurchaseOrderDAO();
			dao4.updateStatusAfterSaveInvoice(sub.getPoRefNo());// หลังจาก save invoice จะต้อง update : poStatus=2, billStatus=1
								
			boolean isItemService = false;
			for (int i = 0; i < item_of_service.length; i++) {
				if(item_of_service[i].contains(sub.getItemCode())) {
					isItemService = true;
				}				
			}
			if(isItemService==false) {
	        	ProcessStockBean bean = new ProcessStockBean();
	        	bean.setItemCode(sub.getItemCode());
	        	bean.setDocDate(sub.getDocDate());
	        	bean.setProcessFlag(0);
	        	bean.setFlowStatus(1);
	        	bean.setProcessType(5);
	        	bean.setProcessCase(1);// สำหรับ BCStkIssue บันทึกเอกสารให้ =1, ลบเอกสารให้=3
	        		        	
	        	p.add(bean);
	        	
	    		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :ProcessStockDAO #mode :add "+
	  				  "#item:"+sub.getItemCode());
// 				BCWinService จะ update: lastBuyPrice ให้กับ item ที่ซื้อเข้ามา แบบ auto อยู่แล้ว	
//	    		new BCItemDAO().updateLastBuyPrice(sub.getItemCode(),sub.getPrice());
	    		
			}
			//###########
		}
// Start: เพื่อ update purchaseOrder
		@SuppressWarnings("unused")
		BCAPInvoice2Form invForm = (BCAPInvoice2Form)form;
// end: เพื่อ update purchaseOrder		
		return true;
	}
	
	@SuppressWarnings("rawtypes")
	public boolean update(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		
		BCAPInvoiceBean  inv = (BCAPInvoiceBean)BCAPInvoiceBO.getObject(form);
		
		//request.setAttribute("docNoFind", inv.getDocNo());
				
		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceDAO #mode :update");
		
		BCAPInvoiceDAO invDao = new BCAPInvoiceDAO();
		ArrayList al = (ArrayList)invDao.find("FROM BCAPInvoiceBean WHERE docNo='"+inv.getDocNo()+"'");
		
		if(al!=null && al.size()>0) {
			
			if(inv.getDocNo().substring(0, 3).equalsIgnoreCase("BCS")) {
				//บันทึกเงินสดย่อย
				BCPayMoneyBean pay = (BCPayMoneyBean)BCPayMoneyBO.getObject(form);			
				BCPayMoneyDAO dao4 = new BCPayMoneyDAO();
				dao4.update(pay.getDocNo(), pay);
				
				// ถ้ามูลค่าสุทธิ < ยอดรวมสินค้า ถือเป็นหัก ณ ที่จ่าย
				BCAPWTaxListDAO dao6 = new BCAPWTaxListDAO();
				ArrayList apwTaxListList = (ArrayList)dao6.find(inv.getDocNo());
				
				BCAPWTaxListBean wTax = (BCAPWTaxListBean)BCAPWTaxListBO.getObject(form);
				if(apwTaxListList!=null && apwTaxListList.size()>0) {
					if(inv.getNetDebtAmount().doubleValue()<inv.getTotalAmount().doubleValue()) {										
						dao6.update(wTax.getDocNo(),wTax);					
						inv.setSumOfWTax(wTax.getwTaxAmount());
						System.out.println("BCAPWTaxListBean: update");
					}else {
						dao6.delete(inv.getDocNo());
						System.out.println("BCAPWTaxListBean: delete");						
					}
				}else {
					if(inv.getNetDebtAmount().doubleValue()<inv.getTotalAmount().doubleValue()) {										
						dao6.add(wTax);						
						inv.setSumOfWTax(wTax.getwTaxAmount());
						System.out.println("BCAPWTaxListBean: add");
					}else {
						dao6.delete(inv.getDocNo());
						System.out.println("BCAPWTaxListBean: delete");
					}
				}
				
			}else if(inv.getDocNo().substring(0, 3).equalsIgnoreCase("CRS") ||
						inv.getDocNo().substring(0, 3).equalsIgnoreCase("CMD")) {				
					BCAPDAO apDao = new BCAPDAO();
					apDao.updateDebtAmount(inv);
			}
			
			// ถ้ามีเลขที่ใบกำกับภาษี (taxNo) ให้เพิ่มใน BCInputTax
			BCInputTaxDAO dao5 = new BCInputTaxDAO();
			ArrayList inputTaxList = (ArrayList)dao5.find(inv.getDocNo());
			
			BCInputTaxBean tax = (BCInputTaxBean)BCInputTaxBO.getObject(form);
			if(inputTaxList!=null && inputTaxList.size()>0) {
				if(inv.getTaxNo()!=null && !inv.getTaxNo().equals("")) {									
					dao5.update(tax.getDocNo(),tax);					
				}else {
					dao5.delete(inv.getDocNo());
				}
			}else {
				if(inv.getTaxNo()!=null && !inv.getTaxNo().equals("")) {
					dao5.add(tax);
				}else {
					dao5.delete(inv.getDocNo());
				}
			}
							
			BCAPInvoiceDAO dao = new BCAPInvoiceDAO();				
			dao.update(inv.getDocNo(),inv);
	//######################
								
			// ใส่ข้อมูล itemCode รายการนั้นใน table: processStock 
			ProcessStockDAO p = new ProcessStockDAO();
			String[] item_of_service = {"A-01", "A-02", "C-3",  "D-03", "D-04", "D-4",  "E-04", "E-05", "E-4",  "E-5",  "E-S-E",
										"F-04", "F-05", "F-06", "F-4",  "F-5",  "F-6",  "G-06", "G-08", "G-10", "G-11", "G-12", 
										"G-13", "G-14", "G-24", "GE",   "H-07", "H-08", "H-15", "HO",   "I-10", "I-16", "IM",
										"INT",  "J-11", "J-17", "K-14", "K-15", "K-16", "K-17", "K-18", "L-18", "L-19", "M-19",
										"M-21", "N-20", "N-22", "O-21", "P-22", "P-23", "Q-23", "R-24", "R-25", "S-25", "SE", "TREEX", "TRECO",
										"SER-006","SES","ST",   "T-26", "U-27", "V-28", "Z-01", "Z-02", "Z-03", "Z-04", "Z-05", "Z-06"};
			
//Start: ใน BC จะต้องเอา itemCode (itemCode ก่อน update + itemCode หลัง update) ใน  invoice ไปใส่ใน  processStock 
//		 ซึ่ง  itemCode ก่อน update เก็บค่าไว้แล้วในตอนแรก อยู่ใน arrayList:al	
//ArrayList al = เก็บitemCode ก่อน update			
			
			ArrayList<ProcessStockBean> itemsEdit = new ArrayList<ProcessStockBean>();// เอาไว้เก็บ item ที่จะแก้ไข ใน processStock 
			
			for (int x = 0; x < al.size(); x++) {
				BCAPInvoiceBean invBean = (BCAPInvoiceBean)al.get(x);

				Iterator it = invBean.getBcAPInvoiceSubs().iterator();
				while(it.hasNext()) {
					BCAPInvoiceSubBean sub = (BCAPInvoiceSubBean)it.next();
											
//					BCStkRequestDAO dao2 = new BCStkRequestDAO();
//					dao2.updateStatus(sub.getStkReqNo(),"1");
//					
//					BCReqConfirmDAO dao3 = new BCReqConfirmDAO();
//					dao3.updateStatus(sub.getStkReqNo(),"1");
									
					//###########
					boolean isItemService = false;
					for (int i = 0; i < item_of_service.length; i++) {
						if(item_of_service[i].contains(sub.getItemCode())) {
							isItemService = true;
						}				
					}
					if(isItemService==false) {
			        	ProcessStockBean bean = new ProcessStockBean();
			        	bean.setItemCode(sub.getItemCode());
			        	bean.setDocDate(sub.getDocDate());
			        	bean.setProcessFlag(0);
			        	bean.setFlowStatus(1);
			        	bean.setProcessType(5);
			        	bean.setProcessCase(2);// สำหรับ BCStkIssue บันทึกเอกสารให้ =1, ลบเอกสารให้=3, แก้ไข=2
			        	
			        	itemsEdit.add(bean);//เก็บ itemCode เฉพาะที่สามารถใส่ใน processStock ของ invoiceSub ตัวก่อน update ไว้ตรวจสอบกับ invoice หลังแก้ไข
			        	p.add(bean);
			        	
			    		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :ProcessStockDAO #mode :update "+
			  				  "#item:"+sub.getItemCode());        				    		
					}
				}		
			}
			
			if(itemsEdit!=null && itemsEdit.size()>0) {
				Iterator it = inv.getBcAPInvoiceSubs().iterator();
				while (it.hasNext()) {
					BCAPInvoiceSubBean sub = (BCAPInvoiceSubBean) it.next();

//					BCStkRequestDAO dao2 = new BCStkRequestDAO();
//					dao2.updateStatus(sub.getStkReqNo(),"2");
//					
//					BCReqConfirmDAO dao3 = new BCReqConfirmDAO();
//					dao3.updateStatus(sub.getStkReqNo(),"2");
					
					boolean isItemRepeat = false; 
					for(int x=0; x<itemsEdit.size(); x++) {
						ProcessStockBean bean = (ProcessStockBean)itemsEdit.get(x);
						if(sub.getItemCode().equalsIgnoreCase(bean.getItemCode())) {
							isItemRepeat = true;
						}
					}
					
					if(isItemRepeat == false) {
			        	ProcessStockBean bean = new ProcessStockBean();
			        	bean.setItemCode(sub.getItemCode());
			        	bean.setDocDate(sub.getDocDate());
			        	bean.setProcessFlag(0);
			        	bean.setFlowStatus(1);
			        	bean.setProcessType(5);
			        	bean.setProcessCase(2);// สำหรับ BCStkIssue บันทึกเอกสารให้ =1, ลบเอกสารให้=3, แก้ไข=2
			        				        	
			        	p.add(bean);
			        	
			    		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :ProcessStockDAO #mode :update "+
			  				  "#item:"+sub.getItemCode());
			    		
					}					
				}
			}
//END ใน BC จะต้องเอา itemCode ใน  invoice ก่อนการ update ไปใส่ใน  processStock ก่อน 													
		}
		
		return true;
	}	

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object getObject(ActionForm form) throws UnsupportedEncodingException {
		
		BCAPInvoiceBean bean = new BCAPInvoiceBean();
		
		BCAPInvoice2Form invForm = (BCAPInvoice2Form)form; 
				
		bean.setDocNo(invForm.getDocNo());
		bean.setTaxNo(invForm.getTaxNo());
		bean.setDocDate( CommonUtils.convertStringToDate(invForm.getDocDate()  ));
		bean.setTaxType(invForm.getTaxType());
		
		bean.setApCode(new String(invForm.getApCode().getBytes("ISO8859_1"), "UTF-8"));
		
		bean.setDepartCode(invForm.getDepartCode());
		bean.setCreditDay(Integer.valueOf(invForm.getCreditDay()));

		bean.setDueDate(bean.getDocDate());
		bean.setStatementDate(bean.getDocDate());
		bean.setStatementState(0);
		
		bean.setTaxRate( Double.valueOf(invForm.getTaxRate()));
		bean.setIsConfirm(0);
		
		String myDescription = new String((invForm.getMyDescription()).getBytes("ISO8859_1"),"UTF-8");		
		if(myDescription.indexOf("(บันทึกข้อมูลจาก  iTTL WebApp.)") == -1) {	
			bean.setMyDescription(myDescription+"(บันทึกข้อมูลจาก  iTTL WebApp.)");
		}else {
			bean.setMyDescription(myDescription);
		}
						
		bean.setBillType(invForm.getBillType());//	ประเภทรายวัน 0=ซื้อสด 1=ซื้อเชื่อ 2=ซื้อบริการสด 3=ซื้อบริการเชื่อ
		bean.setBillGroup(invForm.getBillGroup());
		bean.setContactCode(invForm.getContactCode());
		bean.setSumOfItemAmount(  Double.valueOf( invForm.getSumOfItemAmount()));
		bean.setDiscountWord(null);
		bean.setDiscountAmount( Double.valueOf( invForm.getDiscountAmount()));
				
		bean.setAfterDiscount( Double.valueOf(invForm.getSumOfItemAmount())- Double.valueOf( invForm.getDiscountAmount()));
		bean.setBeforeTaxAmount(bean.getAfterDiscount());
		bean.setTaxAmount( Double.valueOf(invForm.getTaxAmount()));
				
		bean.setTotalAmount( Double.valueOf( invForm.getTotalAmount()));
		bean.setDiscountCase(0);
		bean.setExceptTaxAmount( Double.valueOf( invForm.getExceptTaxAmount()));
		bean.setZeroTaxAmount(0.0);
		
				
		bean.setSumCashAmount(0.0);
		bean.setSumChqAmount(0.0);
		bean.setSumBankAmount(0.0);
		bean.setDepositIncTax(0);
		
		bean.setSumOfDeposit1(0.0);
		bean.setSumOfDeposit2(0.0);
		bean.setSumOfWTax(0.0);
		
		bean.setNetDebtAmount( Double.valueOf(invForm.getNetAmount()));
		bean.setHomeAmount( bean.getNetDebtAmount());
		
		System.out.println("invForm.getNetAmount() = "+invForm.getNetAmount());
		System.out.println("bean.getNetDebtAmount() = "+bean.getNetDebtAmount());
		
		bean.setOtherIncome(0.0);
		bean.setOtherExpense(0.0);
		bean.setExcessAmount1(0.0);
		bean.setExcessAmount2(0.0);
		
		bean.setCurrencyCode(invForm.getCurrencyCode());
		bean.setExchangeRate( Double.valueOf(invForm.getExchangeRate()));
		
		// billType = 0 ซื้อสด, 2=ซื้อบริการสด
		if(bean.getBillType()==0 || bean.getBillType()==2 || 
				bean.getDocNo().substring(0, 3).equalsIgnoreCase("BCS")) {
			bean.setGlFormat("P03-2");
			bean.setBillBalance(0.0);
			bean.setPayBillAmount(0.0);
			bean.setPettyCashAmount( Double.valueOf( invForm.getPayAmount()));
			
		}else {//ที่เหลือคือ CMD, CRS
			
			if(bean.getBillType()==3) {
				bean.setGlFormat("P04");
			}else {
				bean.setGlFormat("P00");
			}
			
			bean.setBillBalance(bean.getTotalAmount());
			bean.setPayBillAmount(Double.valueOf(invForm.getNetAmount()));
			bean.setPettyCashAmount( 0.0);
			
		}		
		
		bean.setGlStartPosting(1);
		bean.setGrBillStatus(0);
		bean.setGrIRBillStatus(0);
		
		bean.setIsPostGL(0);		
		bean.setIsCancel(0);
		bean.setIsCreditNote(0);
		bean.setIsDebitNote(0);
		bean.setIsProcessOK(0);
		
		bean.setIsCompleteSave(1);
		bean.setGlTransData(0);
		
		bean.setAllocateCode(invForm.getAllocateCode());				
		bean.setProjectCode(invForm.getProjectCode());
		bean.setRecurName(null);
		bean.setExchangeProfit(0.0);
		bean.setCreatorCode(invForm.getCreatorCode());
		bean.setCreateDateTime(new Date());
		
		bean.setIttl_payment(invForm.getIttl_payment());
		
		bean.setPrepayAmount(  Double.valueOf(invForm.getNetAmount()));
		
		HashSet hashSet = new HashSet();			
		
		for(int i=0; i<invForm.getItemCode().length; i++ ) {
											
			BCAPInvoiceSubBean sub = new BCAPInvoiceSubBean();
			sub.setMyType(2);
			sub.setTaxNo(bean.getTaxNo());
			sub.setTaxType(bean.getTaxType());
			sub.setItemCode(invForm.getItemCode()[i]);																					
			sub.setDocDate(bean.getDocDate());
			sub.setApCode(bean.getApCode());
			sub.setDepartCode(invForm.getLineItem_departCode()[i]);
			sub.setMyDescription(invForm.getLineItem_myDescription()[i]  );
			sub.setItemName(new String((invForm.getItemName()[i]).getBytes("ISO8859_1"),"UTF-8"));
			sub.setWhCode(invForm.getLineItem_whCode()[i] );
			sub.setShelfCode(invForm.getLineItem_shelfCode()[i] );
			sub.setCnQty(Double.valueOf(invForm.getQty()[i] ));			
			sub.setGrRemainQty(0.0);			
			sub.setQty(Double.valueOf(invForm.getQty()[i]));						
			sub.setPrice(Double.valueOf( invForm.getPrice()[i]));
			
			if(CommonUtils.isNumberPercent(invForm.getLineItemDiscountAmount()[i])) {
				sub.setDiscountWord(invForm.getLineItemDiscountAmount()[i]);
				double percent1 = Double.valueOf( invForm.getLineItemDiscountAmount()[i].substring(0, invForm.getLineItemDiscountAmount()[i].length()-1) );
				
				DecimalFormat f = new DecimalFormat("#.00");
				double subDiscountAmount = Double.valueOf( f.format(sub.getQty()* sub.getPrice()*percent1/100));
				sub.setDiscountAmount(subDiscountAmount);
			}else {
				sub.setDiscountWord(invForm.getLineItemDiscountAmount() [i] );
				sub.setDiscountAmount(Double.valueOf(invForm.getLineItemDiscountAmount() [i] ));
			}
//			sub.setDiscountAmount(Double.valueOf(invForm.getQty() [i] )*Double.valueOf(invForm.getPrice() [i] )-Double.valueOf( invForm.getAmount()[i] ));
						
			sub.setAmount( Double.valueOf( invForm.getAmount()[i] ));			
			sub.setNetAmount(sub.getAmount());
			sub.setHomeAmount(sub.getAmount());
			sub.setBalanceAmount(sub.getAmount());
			sub.setSumOfExpCost(0.0);
			sub.setUnitCode(invForm.getUnitCode()[i]);
			sub.setOppositeQty(0.0);
			sub.setPoRefNo(invForm.getLineItem_poRefNo()[i] );
			
			System.out.println("sub.getPoRefNo()="+sub.getPoRefNo());
			
			sub.setStockType(1);
			sub.setExceptTax(0);
			sub.setTransState(0);			
			sub.setIsCancel(0);
			sub.setLineNumber(i+1);
			sub.setAllocateCode(invForm.getLineItem_allocateCode()[i]);			
			sub.setProjectCode(invForm.getLineItem_projectCode()[i]);			
			sub.setCurrencyCode(bean.getCurrencyCode());
			sub.setExchangeRate(bean.getExchangeRate());
			sub.setIsPromotion(0);
			sub.setPoRefLinenum(0);
			
			try { 
				sub.setStatusReceive(Integer.valueOf(invForm.getLineItem_statusReceive()[i]));	
			} catch (Exception e) {
				sub.setStatusReceive(0);
			}
			
			sub.setTaxRate(Double.valueOf(invForm.getTaxRate()));
			sub.setPackingRate1(1.0);
			sub.setPackingRate2(1.0);
			sub.setIsProcess(0);
			sub.setIslockCost(0);
			sub.setDiscCashCard(0);
			sub.setCreatorCode(bean.getCreatorCode());
			sub.setCreateDateTime(bean.getCreateDateTime());
									
			sub.setBcAPInvoice(bean);
			
			if(invForm.getIttl_rowOrderOfStkReq()[i]==null ||
					invForm.getIttl_rowOrderOfStkReq()[i].equals("")) {
				invForm.getIttl_rowOrderOfStkReq()[i] = "0";
			}
			sub.setIttl_rowOrderOfStkReq(Integer.valueOf(invForm.getIttl_rowOrderOfStkReq()[i]));
			sub.setIttl_purchaseCode(invForm.getIttl_purchaseCode()[i]);
			sub.setStkReqNo(invForm.getStkReqNo()[i]);
			hashSet.add(sub);			
		}
		
		bean.setBcAPInvoiceSubs(hashSet);										
		
		return bean;
	}

	@SuppressWarnings("rawtypes")
	public ArrayList find(HttpServletRequest request) throws UnsupportedEncodingException {
		
		@SuppressWarnings("unused")
		String userName = (String)request.getSession().getAttribute("userName");			
		String monthFind = (String)request.getParameter("monthFind");
		String yearFind = (String)request.getParameter("yearFind");
		@SuppressWarnings("unused")
		String typeDocNoFind = (String)request.getParameter("typeDocNoFind");
		
		String docNoFind = (String)request.getParameter("docNoFind");
		@SuppressWarnings("unused")
		String preDocNo  = (String)request.getSession().getAttribute("preDocNo")+"-PR";
		@SuppressWarnings("unused")
		int userLevel =  (Integer)request.getSession().getAttribute("userLevel");		
				
		if(monthFind==null) {			
			monthFind = CommonUtils.getCurrentDateFormat("MM");										
		}
		
		if(yearFind==null) {
			yearFind = CommonUtils.getCurrentDateFormat("yyyyy");
			
			if (Integer.parseInt(yearFind)<2500) {								
				yearFind = (""+(Integer.parseInt(yearFind)+543)).substring(2);			
			}else {
				yearFind = yearFind.substring(2);
			}			
		}
				
		request.getSession().setAttribute("monthFind", monthFind);
		request.getSession().setAttribute("yearFind", yearFind);
		
		String hql = "";
		if(docNoFind==null||docNoFind.trim().equals("")) {
			hql = "FROM BCAPInvoiceShowBean s  " +
					 "WHERE " + 
					 "  s.docNo like 'BCS-"+yearFind+monthFind+"%' "+
					 " OR s.docNo like 'CRS-"+yearFind+monthFind+"%' "+
					 " OR s.docNo like 'CMD-"+yearFind+monthFind+"%' "+
					 "ORDER BY s.docNo asc";			
		}else {
			docNoFind = new String(docNoFind.getBytes("ISO8859_1"),"UTF-8");
			hql = "FROM BCAPInvoiceShowBean s  " +
					 "WHERE ( s.docNo like '%"+docNoFind.trim()+"%' or "+
					 " 			s.billGroup like '%"+docNoFind.trim()+"%' or "+
					 " 			s.taxNo like '%"+docNoFind.trim()+"%' or "+
					 " 			s.apCode like '%"+docNoFind.trim()+"%' ) "+					 
					 " AND (s.docNo like 'BCS%' OR "+
					 " s.docNo like 'CRS%' OR"+
					 " s.docNo like 'CMD%') "+					 
					 "ORDER BY s.docNo asc";
			request.getSession().setAttribute("docNoFind", docNoFind.trim());
		}
		System.out.println(hql);
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		List results = dao.find(hql);
		
		return (ArrayList)results;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object findForm(HttpServletRequest request)  {
		
		BCAPInvoice2Form form = new BCAPInvoice2Form();
		
		String docNo = (String)request.getParameter("docNo");
		System.out.println("#docNo :"+docNo);
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();	
		String hql = "FROM BCAPInvoiceBean h " +
				" WHERE upper(h.docNo) = '"+docNo.toUpperCase()+"' ";
				
		List results = dao.find(hql);
		
		if (results!=null && results.size()>0) {
			
			//System.out.println("size="+results.size());
			
			for(int i=0; i<results.size(); i++) {				
				BCAPInvoiceBean s2 = (BCAPInvoiceBean)results.get(i);
				
				form.setDocNo(s2.getDocNo());
				form.setTaxNo(s2.getTaxNo());
				form.setDocDate(CommonUtils.convertDateToString(s2.getDocDate()));
				form.setMyDescription(s2.getMyDescription());
				form.setContactCode(s2.getContactCode());
				
				form.setTaxType(s2.getTaxType());
				form.setApCode(s2.getApCode());
				form.setDepartCode(s2.getDepartCode());
				
				form.setTaxRate(""+s2.getTaxRate());

				form.setBillType(s2.getBillType());//	ประเภทรายวัน 0=ซื้อสด 1=ซื้อเชื่อ 2=ซื้อบริการสด 3=ซื้อบริการเชื่อ
				
				form.setBillGroup(s2.getBillGroup());
				
				form.setIttl_payment(s2.getIttl_payment());
				
				form.setSumOfItemAmount(""+s2.getSumOfItemAmount());
				form.setDiscountAmount(""+s2.getDiscountAmount());												
						
				form.setTaxAmount(""+s2.getTaxAmount());	
				form.setTotalAmount(""+s2.getTotalAmount());											
				
				form.setPayAmount(""+s2.getPettyCashAmount());
				form.setNetAmount(""+s2.getNetDebtAmount());		
				form.setExchangeRate(""+s2.getExchangeRate());																				
				
				form.setAllocateCode(s2.getAllocateCode());
				form.setProjectCode(s2.getProjectCode());				
				
				form.setCreatorCode(s2.getCreatorCode());																																	
				form.setStatementDate(CommonUtils.convertDateToString(s2.getStatementDate()));
				form.setDueDate(CommonUtils.convertDateToString(s2.getDueDate()));
				form.setCreditDay(""+s2.getCreditDay());
				
				ArrayList al = new ArrayList();
				
				for(Object o: s2.getBcAPInvoiceSubs()) {
					BCAPInvoiceSubBean sub2 = (BCAPInvoiceSubBean)o;
					al.add(sub2);					
				}
				
				form.setInvoiceSub(al);
			}			
		}	
		
		if(form.getTaxNo()!=null) {			 
			BCInputTaxDAO taxDao = new BCInputTaxDAO();
			ArrayList al = (ArrayList)taxDao.find(form.getDocNo());
			
			if(al!=null && al.size()>0) {				
				form.setTaxNo(((BCInputTaxBean)al.get(0)).getTaxNo());
				form.setTaxDate(CommonUtils.convertDateToString(((BCInputTaxBean)al.get(0)).getTaxDate()));
			}						
		}
		
		if(form.getPayAmount()!=null && form.getPayAmount().trim().length()>0) {
			BCPayMoneyDAO payDao = new BCPayMoneyDAO();
			ArrayList al = (ArrayList)payDao.find(form.getDocNo());
			
			if(al!=null && al.size()>0) {				
				form.setRefNo(((BCPayMoneyBean)al.get(0)).getRefNo());				
			}			
		}
		
		if(form.getApCode() !=null && form.getApCode().trim().length()>0) {
			BCAPDAO apDao = new BCAPDAO();
			ArrayList al = (ArrayList)apDao.find(form.getApCode().trim());
			
			if(al!=null && al.size()>0) {
				
				try {
					form.setApName (new String(  ((BCAPBean)al.get(0)).getName1() ));//.getBytes("ISO8859_1"),"UTF-8"
					
				} catch (Exception e) {
					System.out.println(e.toString());
				}
			}			
		}		
		
		return form;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void setForm(HttpServletRequest request) throws UnsupportedEncodingException {
		
		//System.out.print("###########################");
		
		BCAPInvoice2Form invForm = (BCAPInvoice2Form)findForm(request);
		
		request.setAttribute("invForm", invForm);		
		//request.setAttribute("resultList1", invForm.getInvoiceSub());
		
		ArrayList al = invForm.getInvoiceSub();
		ArrayList al2 = new ArrayList();
		for (int j = 0; j < al.size(); j++) {				
			BCAPInvoiceSubBean sub = (BCAPInvoiceSubBean)al.get(j);
			
			BCPurchaseOrderShowBean bean = new BCPurchaseOrderShowBean();
			
			bean.setLineNumber(""+(j+1));
			bean.setItemCode(sub.getItemCode());
			bean.setItemName(sub.getItemName());
			bean.setUnitCode(sub.getUnitCode());
			bean.setQty(""+sub.getQty());
			bean.setPrice(""+sub.getPrice());					
			bean.setLineItemDiscountAmount(""+sub.getDiscountAmount());
			bean.setAmount(""+sub.getAmount());
			bean.setLineItem_whCode(sub.getWhCode());
			bean.setLineItem_shelfCode(sub.getShelfCode());
			bean.setLineItem_statusReceive(""+sub.getStatusReceive());
			
			bean.setLineItem_departCode(sub.getDepartCode());	
			bean.setLineItem_projectCode(sub.getProjectCode());
			bean.setLineItem_allocateCode(sub.getAllocateCode());

			bean.setLineItem_myDescription(sub.getMyDescription());
			bean.setLineItem_poRefNo(sub.getPoRefNo());						
			bean.setLineItem_netAmount(""+sub.getNetAmount());
			bean.setLineItem_homeAmount(""+sub.getHomeAmount());
			
			bean.setStkReqNo(sub.getStkReqNo());
			
			if(sub.getPoRefNo()!=null) {
				String hql = "FROM BCPurchaseOrderSubShowBean WHERE docNo ='"+sub.getPoRefNo().trim()+"'";
				BCPurchaseOrderDAO poDao = new BCPurchaseOrderDAO();
				
				System.out.println(hql);
				List poList = poDao.find(hql);
				if(poList!=null && poList.size()>0) {
					BCPurchaseOrderSubShowBean poShow = (BCPurchaseOrderSubShowBean)poList.get(0);
					bean.setIttl_rowOrderOfStkReq(poShow.getIttl_rowOrderOfStkReq());
				}
			}
				
			al2.add(bean);
								
		}				
		request.getSession().setAttribute("resultList1", al2);
		request.setAttribute("countId", al2.size());
						
		request.setAttribute("creatorCode", invForm.getCreatorCode());
		
		request.setAttribute("billType", invForm.getBillType());
		request.setAttribute("taxType", invForm.getTaxType());
		request.setAttribute("docNo", invForm.getDocNo());
		request.setAttribute("docDate", invForm.getDocDate());
		request.setAttribute("taxNo", invForm.getTaxNo());
		request.setAttribute("taxDate", invForm.getTaxDate());
		request.setAttribute("apCode", invForm.getApCode());
		
		request.setAttribute("apName", invForm.getApName());
		request.setAttribute("myDescription", invForm.getMyDescription());
		
		request.setAttribute("ittl_payment", invForm.getIttl_payment());
		
		request.setAttribute("contactCode", invForm.getContactCode());
		request.setAttribute("sumOfItemAmount", invForm.getSumOfItemAmount());
		request.setAttribute("departCode", invForm.getDepartCode());
		request.setAttribute("projectCode", invForm.getProjectCode());
		request.setAttribute("discountAmount", invForm.getDiscountAmount());
		request.setAttribute("allocateCode", invForm.getAllocateCode());
		request.setAttribute("statementDate", invForm.getStatementDate());
		request.setAttribute("taxAmount", invForm.getTaxAmount());
		request.setAttribute("creditDay", invForm.getCreditDay());
		request.setAttribute("dueDate", invForm.getDueDate());
		request.setAttribute("totalAmount", invForm.getTotalAmount());
		request.setAttribute("billGroup", invForm.getBillGroup());
		request.setAttribute("taxRate", invForm.getTaxRate());
		request.setAttribute("exceptTaxAmount", invForm.getExceptTaxAmount());
		request.setAttribute("currencyCode", invForm.getCurrencyCode());
		request.setAttribute("exchangeRate", invForm.getExchangeRate());
		request.setAttribute("netAmount", invForm.getNetAmount());
		request.setAttribute("payAmount", invForm.getPayAmount());
		request.setAttribute("refNo", invForm.getRefNo());		
		
	}

	public void setMoreDetailsForm(HttpServletRequest request) {
		
		
		String 	lineItem_whCode	= 	(String)request.getParameter("lineItem_whCode");
		String	lineItem_shelfCode 	=	(String)request.getParameter("lineItem_shelfCode");		
		String 	lineItem_statusReceive= 	(String)request.getParameter("lineItem_statusReceive");
		String	lineItem_departCode=	(String)request.getParameter("lineItem_departCode");
		String	lineItem_projectCode=	(String)request.getParameter("lineItem_projectCode");
		String	lineItem_allocateCode=	(String)request.getParameter("lineItem_allocateCode");
		String	lineItem_myDescription=	(String)request.getParameter("lineItem_myDescription");
		String	lineItem_poRefNo=	(String)request.getParameter("lineItem_poRefNo");
		String	lineItem_netAmount=	(String)request.getParameter("lineItem_netAmount");
		String	lineItem_homeAmount=	(String)request.getParameter("lineItem_homeAmount");
		String	lineNumber		=	(String)request.getParameter("lineNumber");
		
		request.setAttribute("whCode", lineItem_whCode);
		request.setAttribute("shelfCode", lineItem_shelfCode);		
		request.setAttribute("statusReceive", lineItem_statusReceive);
		request.setAttribute("departCode", lineItem_departCode);
		request.setAttribute("projectCode", lineItem_projectCode);
		request.setAttribute("allocateCode", lineItem_allocateCode);
		request.setAttribute("myDescription", lineItem_myDescription);
		request.setAttribute("poRefNo", lineItem_poRefNo);
		request.setAttribute("netAmount", lineItem_netAmount);
		request.setAttribute("homeAmount", lineItem_homeAmount);
		request.setAttribute("lineNumber", lineNumber);				
		
	}

	public void setPage(HttpServletRequest request, String hql) {
//		System.out.println("hql="+hql);
		int pageNumber = 1, maxEntriesPerPage=5, lineNumber=1;		
		try {			
			pageNumber = Integer.parseInt(request.getParameter("page"));
		} catch (Exception e) {}
		
		if(request.getParameter("maxEntriesPerPage")!=null) {
			maxEntriesPerPage = Integer.parseInt(request.getParameter("maxEntriesPerPage"));			
		}
		if(request.getParameter("lineNumber")!=null) {
			request.setAttribute("lineNumber", request.getParameter("lineNumber"));
		}else {
			request.setAttribute("lineNumber", lineNumber);
		}
				
//		Page page = CommonUtils.getHibernatePage(hql, pageNumber, maxEntriesPerPage);				
		Page page = CommonUtils.getHibernateScrollableResultsPage(hql, pageNumber, maxEntriesPerPage);		
		
		request.setAttribute("maxEntriesPerPage", maxEntriesPerPage);
		request.setAttribute("allElement", page.getAllElement());
		System.out.println(page.getAllElement());
	
		if(page.getAllElement()>0) {
			
			request.setAttribute("itemResults", page.getResultList() );
			request.setAttribute("offset", (pageNumber-1)*maxEntriesPerPage);
			request.setAttribute("currentPage", page.getCurrentPage());
			
			if(page.isNextPage()==true) {
				request.setAttribute("nextPage", page.getCurrentPage()+1);
			}
			
			if(page.isPreviousPage()==true) {
				request.setAttribute("previousPage", page.getCurrentPage()-1);
			}
			
			if(page.isFirstPage()==true) {
				request.setAttribute("firstPage", 1);
			}		
			
			if(page.isLastPage()==true && page.getMaxEntriesPerPage()!=0) {
				if(page.getAllElement()%page.getMaxEntriesPerPage()==0) {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage());	
				}else {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage()+1);
				}						
			}
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ArrayList findPO(ActionForm form, HttpServletRequest request) {

		POFindForm invForm =(POFindForm)form;
		String docNo = "";
		for(int i=0; i<invForm.getDocNoArray().length; i++) {
			docNo = docNo +"'"+ invForm.getDocNoArray()[i].trim() + "',";
		}
		if(docNo.length()>0) {
			docNo = docNo.substring(0, docNo.length()-1);
		}
		
		String hql = "FROM BCPurchaseOrderBean s  " +
		 "WHERE  " +
		 " s.docNo in ( "+docNo+" )  ";		
		
		System.out.println(hql);
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		ArrayList results = (ArrayList)dao.find(hql);
				
		ArrayList al = new ArrayList();
		
		NumberFormat formatter = new DecimalFormat("0.##");
		double amount=0;
		if(results !=null && results.size()>0) {
			
			int id=0;
			for(int i=0; i<results.size(); i++) {
				
				BCPurchaseOrderBean poBean = (BCPurchaseOrderBean)results.get(i);
				Iterator it = poBean.getBcPurchaseOrderSubs().iterator();
				while (it.hasNext()) {
					BCPurchaseOrderSubBean poSub = (BCPurchaseOrderSubBean) it.next();
					
					BCPurchaseOrderShowBean bean = new BCPurchaseOrderShowBean();
					
					if(poSub.getIttl_rowOrderOfStkReq()!=null) {
						bean.setIttl_rowOrderOfStkReq(poSub.getIttl_rowOrderOfStkReq());
					}else {
						bean.setIttl_rowOrderOfStkReq(0);
					}
					bean.setNumberForSort(""+poSub.getLineNumber());
					
					bean.setDocNo(poBean.getDocNo());
		        	bean.setLineNumber(""+(++id));
		        	bean.setItemCode(poSub.getItemCode());
		        	bean.setItemName(poSub.getItemName()+ " "+poSub.getMyDescription());
		        	bean.setUnitCode(poSub.getUnitCode());
		        	bean.setQty(formatter.format(poSub.getQty()));
		        	
		        	bean.setIttl_purchaseCode(poSub.getIttl_purchaseCode());
		        	bean.setStkReqNo(poSub.getStkReqNo());		        	
		        	bean.setConfirmNo(poSub.getConfirmNo());		        			        			        	
		        	bean.setDepartCode(poSub.getDepartCode());
		        	bean.setProjectCode(poSub.getProjectCode());
		        	bean.setWhCode(poSub.getWhCode());
		        	bean.setShelfCode(poSub.getShelfCode());				        	
		        	bean.setLineItem_whCode(poSub.getWhCode());
		        	bean.setLineItem_shelfCode(poSub.getShelfCode());
		        	bean.setLineItem_statusReceive("0");
		        	bean.setLineItem_departCode(poSub.getDepartCode());				        	
		        	bean.setLineItem_projectCode(poSub.getProjectCode());
		        	bean.setLineItem_poRefNo(poBean.getDocNo());
		        	
		        	bean.setPrice(""+poSub.getPrice());
		        	if(poSub.getDiscountWord()!=null) {
		        		bean.setLineItemDiscountAmount(""+poSub.getDiscountWord());	
		        	}else {
		        		bean.setLineItemDiscountAmount("0");
		        	}
		        		
		        	
		        	bean.setAmount(""+poSub.getAmount());
		        	
		        	amount = amount + poSub.getAmount();
		        	
		        	request.setAttribute("departCode", bean.getDepartCode());
		        	request.setAttribute("projectCode", bean.getProjectCode());
		        	al.add(bean);		        	
				}
				request.setAttribute("apCode", poBean.getApCode());
				request.setAttribute("apName", poBean.getTempMyDesc7());
				request.setAttribute("sumOfItemAmount", poBean.getSumOfItemAmount());
				request.setAttribute("taxAmount", poBean.getTaxAmount());
				request.setAttribute("totalAmount", poBean.getTotalAmount());
				request.setAttribute("netAmount", poBean.getNetAmount());
				request.setAttribute("taxRate", "7.00");
				request.setAttribute("exchangeRate", "1.00");
				request.setAttribute("discountAmount", "0.00");
				request.setAttribute("exceptTaxAmount", "0.00");
				
				//end new
				
//				BCReqConfirmBean f = (BCReqConfirmBean)results.get(i);
//				
//		    	Iterator it = f.getBcReqConfirmSubs().iterator();		    	
//		        while(it.hasNext()) {
//		        	BCReqConfirmSubBean sub = (BCReqConfirmSubBean)it.next();
//		        	
//		        	BCPurchaseOrderShowBean bean = new BCPurchaseOrderShowBean();
//		        	
//		        	bean.setLineNumber(""+(++id));
//		        	bean.setItemCode(sub.getItemCode());
//		        	bean.setItemName(sub.getItemName());
//		        	bean.setUnitCode(sub.getUnitCode());
//		        	bean.setQty(""+sub.getQty());		        	
//		        	bean.setIttl_purchaseCode(sub.getStkRequestNo());
//		        	bean.setStkReqNo(sub.getStkRequestNo());		        	
//		        	bean.setConfirmNo(f.getDocNo());		        			        			        	
//		        	bean.setDepartCode(sub.getDepartCode());
//		        	
//		        	hql = "FROM BCStkRequestBean WHERE docNo='"+f.getDocNo()+"'";
//		        	BCStkRequestDAO dao2 = new BCStkRequestDAO();
//		        	ArrayList al2 = (ArrayList)dao2.find(hql);
//		        	
//		        	for(int j=0; j<al2.size(); j++) {		        		
//		        		BCStkRequestBean stk = (BCStkRequestBean)al2.get(j);
//		        		bean.setProjectCode(stk.getProjectCode());
//		        		
//				    	Iterator it2 = stk.getBcStkRequestSubs().iterator();
//				    	int x =0;
//				        while(it2.hasNext()) {
//				        	BCStkRequestSubBean sub2 = (BCStkRequestSubBean)it2.next();				        	
//				        	bean.setWhCode("10");
//				        	bean.setShelfCode("10");				        	
//				        	bean.setLineItem_whCode("10");
//				        	bean.setLineItem_shelfCode("10");
//				        	bean.setLineItem_statusReceive("0");
//				        	bean.setLineItem_departCode(sub.getDepartCode());				        	
//				        	bean.setLineItem_projectCode(sub2.getProjectCode());
//				        					        	
//				        	if(sub2.getItemCode().equals(sub.getItemCode()) && 
//				        			sub2.getItemName().equals(sub.getItemName() )) {
//				        		bean.setUnitName(sub2.getIttl_unitName());
//				        	}				        	
//				        }
//		        	}
//							        			        	
//		        	request.setAttribute("departCode", bean.getDepartCode());
//		        	request.setAttribute("projectCode", bean.getProjectCode());
//		        	al.add(bean);		        		
//		        }
			}
			

		}	
// Start : เรียงลำดับ lineItem ตามลำดับการเลือก docNo;		
		ArrayList alSort = new ArrayList();
		for(int i=0; i<invForm.getDocNoArray().length; i++) {
			docNo = docNo +"'"+ invForm.getDocNoArray()[i].trim() + "',";
			
			for(int j=0; j<al.size(); j++) {
				BCPurchaseOrderShowBean po = (BCPurchaseOrderShowBean)al.get(j);
				if(invForm.getDocNoArray()[i].trim().equals(po.getDocNo())) {
					po.setNumberForSort(""+i+po.getNumberForSort());
					alSort.add(po);
				}
			}			
		}
// END : เรียงลำดับ lineItem ตามลำดับการเลือก docNo โดยใช้ ลำดับของ poDocNo ที่เลือกเข้ามา + lineNumber ของ itemใน po ใบนั้นๆ;
		
		Collections.sort(alSort);
		
		return alSort;//alSort;//al;
	}

	@SuppressWarnings("rawtypes")
	public void showFind(HttpServletRequest request) throws UnsupportedEncodingException {
		@SuppressWarnings("unused")
		String userName = (String)request.getSession().getAttribute("userName");			
		String monthFind = (String)request.getParameter("monthFind");
		String yearFind = (String)request.getParameter("yearFind");

		@SuppressWarnings("unused")
		String preDocNo  = (String)request.getSession().getAttribute("preDocNo")+"";
		@SuppressWarnings("unused")
		int userLevel =  (Integer)request.getSession().getAttribute("userLevel");		

		String	itemFind = "";
		if(request.getParameter("itemFind")!=null) {
			itemFind = ((String)request.getParameter("itemFind"));
			itemFind = new String(itemFind.getBytes("ISO8859_1"),"UTF-8");
			request.setAttribute("itemFind", itemFind.trim());
		}		
		
		if(monthFind==null) {			
			monthFind = CommonUtils.getCurrentDateFormat("MM");										
		}
		
		if(yearFind==null) {
			yearFind = CommonUtils.getCurrentDateFormat("yyyyy");
			
			if (Integer.parseInt(yearFind)<2500) {								
				yearFind = (""+(Integer.parseInt(yearFind)+543)).substring(2);			
			}else {
				yearFind = yearFind.substring(2);
			}			
		}
				
		request.getSession().setAttribute("monthFind", monthFind);
		request.getSession().setAttribute("yearFind", yearFind);
		
		String hql = "";
		if(itemFind==null||itemFind.trim().equals("")) {
			hql = "FROM BCAPInvoiceBean   " +
					 " WHERE (docNo like 'BCS%' or docNo like 'CRS%' or docNo like 'CMD%') " +
					 " ORDER BY docNo desc";			
		}else {
			
			hql = "FROM BCAPInvoiceSubShowBean WHERE poRefNo like '%"+itemFind.trim()+"%'";
			BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
			List invList = dao.find(hql);
			String docNo = " or docNo in (";
			if(invList!=null && invList.size()>0) {
				for (int i = 0; i < invList.size(); i++) {
					BCAPInvoiceSubShowBean b = (BCAPInvoiceSubShowBean)invList.get(i);
					docNo += "'"+b.getDocNo()+"',";
				}
				docNo = docNo.substring(0, docNo.length()-1)+")";
			}
			
			hql = "FROM BCAPInvoiceBean  " +
			 		 " WHERE (docNo like 'BCS%' or docNo like 'CRS%' or docNo like 'CMD%') " +
					 " and (docNo  like '%"+itemFind.trim()+"%' or "+					 
					 "      taxNo  like '%"+itemFind.trim()+"%' or "+	
					 "      apCode like '%"+itemFind.trim()+"%' ";
			if(invList!=null && invList.size()>0) {
				hql = hql + docNo +" ) ORDER BY docNo desc"; 
			}else {
				hql = hql +" ) ORDER BY docNo desc";
			}
					 
		}
		System.out.println(hql);
		Page.setPageForInvoice(request, hql);	
		
		  
	}

	 
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ArrayList<ITTL_P2> getP2List(BCAPInvoiceBean inv) {
		ArrayList<ITTL_P2> al = new ArrayList<ITTL_P2>();
		HashSet poSet = new HashSet();
		
		
		Iterator it = inv.getBcAPInvoiceSubs().iterator();
		while (it.hasNext()) {
			BCAPInvoiceSubBean psub = (BCAPInvoiceSubBean) it.next();
			
			poSet.add(psub.getPoRefNo());
			
			ITTL_P2 p2 = new ITTL_P2();
			p2.setTaxNo(inv.getTaxNo());
			p2.setDocNo(inv.getDocNo());
			p2.setPoRefNo(psub.getPoRefNo());
			p2.setItemCode(psub.getItemCode());
			p2.setItemName(psub.getItemName());
			p2.setQty(psub.getQty());
			p2.setPrice(psub.getPrice());
			p2.setDiscountWordLineItem(psub.getDiscountWord());
			p2.setDiscountAmountLineItem(psub.getDiscountAmount());
			p2.setAmount(psub.getAmount());
			
			p2.setLineNumber(psub.getLineNumber());
//			sumOfItemAmountOfPO;
//			taxAmountOfPO;
//			totalAmountOfPO;
			p2.setSumOfItemAmountOfInvoice(inv.getSumOfItemAmount());
			p2.setTaxAmountOfInvoice(inv.getTaxAmount());
			p2.setTotalAmountOfInvoice(inv.getTotalAmount());
			p2.setBillGroup(inv.getBillGroup());
			p2.setDocDate(inv.getDocDate());			
			p2.setApCode(inv.getApCode());
			p2.setIttl_purchaseCode(psub.getIttl_purchaseCode());		
			p2.setIttl_payment(inv.getIttl_payment());
			
			p2.setCreatorCode(inv.getCreatorCode());
			p2.setCreateDateTime(inv.getCreateDateTime());
			
			p2.setUnitCode(psub.getUnitCode());
//			p2.setApName(inv.getap)
//			p2.setPoDate(poDate);
//			tempMyDesc3
//			tempMyDesc4
//			tempMyDesc5
//			tempMyDesc6
//			stkReqNo
//			unitName
			al.add(p2);
		}
		
		double sumTaxAmountOfPO = 0; //เก็บยอดรวมของ taxAmountOfPO เพื่อเอามาตรวจสอบกับ  inv.getTaxAmount() ว่าเท่ากันหรือไม่ (ถ้าไม่จะได้ปัดเศษ)
		String poRefNo = "";		// เก็บไว้สำหรับกรณีถ้า taxAmount มีการปัดเศษจากการบันทึกจะได้เอา poRefNo ตัวนี้ไปใช้ได้เลยว (เลือก po มา 1 ใบเพื่อปัดเศษ)
		Iterator itPOSet = poSet.iterator();
		while (itPOSet.hasNext()) {
			poRefNo = (String) itPOSet.next();
			double sumOfItemAmountOfPO = 0;
			double taxAmountOfPO = 0;
			double totalAmountOfPO = 0;
			//start : sum ยอดรวมของแต่ล่ะ po
			for (int i = 0; i < al.size(); i++) {
				ITTL_P2 p2 = (ITTL_P2)al.get(i);
				
				if(p2.getPoRefNo().equals(poRefNo)) {
					sumOfItemAmountOfPO +=p2.getAmount().doubleValue();	
				}
			}						
			if(inv.getTaxAmount().doubleValue()>0) {
				DecimalFormat df = new DecimalFormat("#####0.00");
				taxAmountOfPO = Double.valueOf( df.format( sumOfItemAmountOfPO * (inv.getTaxRate().doubleValue() / 100d) ));
				
				DecimalFormat df3 = new DecimalFormat("#####0.000");
				double taxAmountOfPO3 = Double.valueOf( df3.format( sumOfItemAmountOfPO * (inv.getTaxRate().doubleValue() / 100d) ));
				
				//System.out.println("taxAmountOfPO = "+taxAmountOfPO+"\t\ttaxAmountOfPO3="+taxAmountOfPO3 +"\t\t\t ->"+(taxAmountOfPO3-taxAmountOfPO));
				
				if( (taxAmountOfPO3-taxAmountOfPO)>=0.005 && (taxAmountOfPO3-taxAmountOfPO)<0.006 ) {
					//System.out.println("yes :0.005");
					//System.out.println(taxAmountOfPO);
					taxAmountOfPO= taxAmountOfPO+0.01;
					//System.out.println(taxAmountOfPO);
				}
				
				sumTaxAmountOfPO += taxAmountOfPO;
			}
			totalAmountOfPO = sumOfItemAmountOfPO+taxAmountOfPO;
			//end : sum ยอดรวมของแต่ล่ะ po
			//start: เอายอดรวมที่ได้ใส่ลงใน po
			for (int i = 0; i < al.size(); i++) {
				ITTL_P2 p2 = (ITTL_P2)al.get(i);
				
				if(p2.getPoRefNo().equals(poRefNo)) {
					p2.setSumOfItemAmountOfPO(sumOfItemAmountOfPO);
					p2.setTaxAmountOfPO(taxAmountOfPO);
					p2.setTotalAmountOfPO(totalAmountOfPO);
				}
			}
			//end: เอายอดรวมที่ได้ใส่ลงใน po			
		}
		
		if(al!=null&& al.size()>0) {
			//System.out.println("\n\n\nsumTaxAmountOfPO!=inv.getTaxAmount().doubleValue() ->"+(sumTaxAmountOfPO!=inv.getTaxAmount().doubleValue()));
			if (sumTaxAmountOfPO!=inv.getTaxAmount().doubleValue()) {
				for (int i = 0; i < al.size(); i++) {
					ITTL_P2 p2 = (ITTL_P2)al.get(i);
					
					if(p2.getPoRefNo().equals(poRefNo)) {
						
						@SuppressWarnings("unused")
						DecimalFormat df = new DecimalFormat("0.000");
												
						if (sumTaxAmountOfPO > inv.getTaxAmount().doubleValue()) {
							//System.out.println("ผลรวม sumTaxAmountOfPO คำนวน มากกว่า taxAmount invoice");
							
							double taxAmountOfPO =     p2.getSumOfItemAmountOfPO().doubleValue() * (inv.getTaxRate().doubleValue() / 100d );
							//System.out.println("i = "+i+"\ttaxAmountOfPO="+taxAmountOfPO+"\t\tp2.getTaxAmountOfPO().doubleValue()="+p2.getTaxAmountOfPO().doubleValue());
							
							if(taxAmountOfPO!=p2.getTaxAmountOfPO().doubleValue()) {
							
								p2.setTaxAmountOfPO(p2.getTaxAmountOfPO().doubleValue() -(sumTaxAmountOfPO-inv.getTaxAmount().doubleValue()));
								p2.setTotalAmountOfPO(p2.getTotalAmountOfPO().doubleValue()-(sumTaxAmountOfPO-inv.getTaxAmount().doubleValue()));
							}
						}else if (sumTaxAmountOfPO < inv.getTaxAmount().doubleValue()) {	
							//System.out.println("ผลรวม sumTaxAmountOfPO คำนวน น้อยกว่า taxAmount invoice");
							
							
							double taxAmountOfPO =  p2.getSumOfItemAmountOfPO().doubleValue() * ( inv.getTaxRate().doubleValue() / 100d  );							
							
							
							if(taxAmountOfPO!=p2.getTaxAmountOfPO().doubleValue()) {
								
								//System.out.println("i = "+i+"\ttaxAmountOfPO="+taxAmountOfPO+
								//		"\t\tp2.getTaxAmountOfPO().doubleValue()="+p2.getTaxAmountOfPO().doubleValue());
								
								p2.setTaxAmountOfPO(p2.getTaxAmountOfPO().doubleValue()+(inv.getTaxAmount().doubleValue()-sumTaxAmountOfPO));
								p2.setTotalAmountOfPO(p2.getTotalAmountOfPO().doubleValue()+(inv.getTaxAmount().doubleValue()-sumTaxAmountOfPO));
							}
						}								
					}
				}			
			}
		}
		
		return al;
	}

	@SuppressWarnings("rawtypes")
	public ArrayList<ITTL_P2> getP2SetPODetails(List poList, ArrayList<ITTL_P2> al) {
		
		for (int i = 0; i < poList.size(); i++) {
			BCPurchaseOrderBean po = (BCPurchaseOrderBean)poList.get(i);
			
			for (int j = 0; j < al.size(); j++) {
				ITTL_P2 p2 = (ITTL_P2)al.get(j);
				
				if(p2.getPoRefNo().equals(po.getDocNo())) {
					p2.setPoDate(po.getDocDate());
					p2.setTempMyDesc3(po.getTempMyDesc3());
					p2.setTempMyDesc4(po.getTempMyDesc4());
					p2.setTempMyDesc5(po.getTempMyDesc5());
					p2.setTempMyDesc6(po.getTempMyDesc6());
					p2.setIsCancel(0);
					p2.setMyDescription(po.getMyDescription());
					Iterator it2 = po.getBcPurchaseOrderSubs().iterator();
					while (it2.hasNext()) {
						BCPurchaseOrderSubBean poSub = (BCPurchaseOrderSubBean) it2.next();
						p2.setStkReqNo(poSub.getStkReqNo());
					//	p2.setUnitName(poSub.getIttl_unitName());
					//	p2.setLineNumber(poSub.getLineNumber());
					}
				}
			}	
		}
//		p2.setApName(inv.getap)
		//			p2.setPoDate(poDate);
		//			tempMyDesc3
		//			tempMyDesc4
		//			tempMyDesc5
		//			tempMyDesc6
		//		stkReqNo
		//		unitName
		
		return al;
	}

	public void summaryInv(ActionForm form, HttpServletRequest request) {
		
		InvFindForm invForm =(InvFindForm)form;		
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		dao.summaryInv(invForm.getDocNoArray(), invForm.getTypeArray());
		
	}

	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	public BCAPInvoiceBean findInv(ActionForm form, HttpServletRequest request) {
		String docNo = (String)request.getParameter("docNo");
		
		BCAPInvoiceBean inv = new BCAPInvoiceBean();

		String hql = "FROM BCAPInvoiceBean " +
		 				" WHERE docNo in ( '"+docNo+"' )  ";		
		
		BCAPInvoiceDAO dao = new BCAPInvoiceDAO();
		ArrayList results = (ArrayList)dao.find(hql);
		
		if(results!=null && results.size()>0) {
			inv = (BCAPInvoiceBean)results.get(0);
			
			List al = new BCAPDAO().find(inv.getApCode());
			if(al.size()>0) {
				BCAPBean ap = (BCAPBean)al.get(0);
				request.setAttribute("apName", ap.getName1());
			}
			
			// Start : เรียงลำดับ lineItem ตามลำดับการเลือก docNo;
			
			ArrayList alSort = new ArrayList();
			
			Iterator it = inv.getBcAPInvoiceSubs().iterator();
			int i=0;
			while (it.hasNext()) {
				BCAPInvoiceSubBean invSub = (BCAPInvoiceSubBean) it.next();
				
				i++;
				BCPurchaseOrderShowBean po = new BCPurchaseOrderShowBean();
				po.setNumberForSort(""+invSub.getLineNumber());
				
				po.setItemCode(invSub.getItemCode());
				po.setItemName(invSub.getItemName());			
				po.setUnitCode(invSub.getUnitCode());
				po.setQty(""+invSub.getQty());
				
				po.setWhCode(invSub.getWhCode());
				po.setShelfCode(invSub.getShelfCode());
				po.setIttl_purchaseCode(invSub.getIttl_purchaseCode());
				
				po.setDepartCode(invSub.getDepartCode());
				po.setProjectCode(invSub.getProjectCode());
								
				//############## สำหรับไว้เก็บค่าของ lineitem ใน invoicesub ################
				po.setIttl_rowOrderOfStkReq(invSub.getIttl_rowOrderOfStkReq());
				po.setLineNumber(""+invSub.getLineNumber());
				po.setPrice(""+invSub.getPrice());
				po.setLineItemDiscountAmount(""+invSub.getDiscountAmount());
				po.setAmount(""+invSub.getAmount());
				po.setLineItem_whCode(invSub.getWhCode());
				po.setLineItem_shelfCode(invSub.getShelfCode());
				po.setLineItem_departCode(invSub.getDepartCode());
				po.setLineItem_projectCode(invSub.getProjectCode());
				po.setLineItem_myDescription(invSub.getMyDescription());
				po.setLineItem_poRefNo(invSub.getPoRefNo());
				po.setLineItem_netAmount(""+invSub.getNetAmount());
				po.setLineItem_homeAmount(""+invSub.getHomeAmount());
				
				alSort.add(po);					
			}
			// END : เรียงลำดับ lineItem ตามลำดับการเลือก docNo โดยใช้ ลำดับของ poDocNo ที่เลือกเข้ามา + lineNumber ของ itemใน po ใบนั้นๆ;
			
			Collections.sort(alSort);
			request.setAttribute("resultList_prpo", alSort);
		}
		
		return inv;
	}

	
	public boolean delete(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		
//		BCAPInvoiceBean  inv = (BCAPInvoiceBean)BCAPInvoiceBO.getObject(form);		
		BCAPInvoice2Form invForm = (BCAPInvoice2Form)form;		

		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceDAO #mode :delete");		
		
		request.setAttribute("docNoDelete", invForm.getDocNo());
		return 	new BCAPInvoiceDAO().deleteInvoice(invForm.getDocNo());
	}

	public boolean update2(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {


//		BCAPInvoice2Form invForm = (BCAPInvoice2Form)form;		

		String user 	 = (String)request.getSession().getAttribute("userName");
		System.out.println(CommonUtils.getDateTimeForStamp()+" #user:"+user+" #use :BCAPInvoiceDAO #mode :update2");		

		BCAPInvoiceBean  inv = (BCAPInvoiceBean)BCAPInvoiceBO.getObject(form);
		inv.setLastEditorCode(user);
		inv.setLastEditDateT(new Date());
		
		request.setAttribute("itemFind", inv.getDocNo());
		return 	new BCAPInvoiceDAO().updateInvoice(form, inv);
	}

	@SuppressWarnings("rawtypes")
	public ArrayList<ITTL_P2> getP2ProjectCode(BCAPInvoiceBean invoice,
			ArrayList<ITTL_P2> al) {
		
		ArrayList<ITTL_P2> p2List = new ArrayList<ITTL_P2>();
		
		Iterator it = invoice.getBcAPInvoiceSubs().iterator();
		while (it.hasNext()) {
			BCAPInvoiceSubBean isub = (BCAPInvoiceSubBean) it.next();
			
			for (ITTL_P2 p2 : al) {
				if(isub.getPoRefNo().equals(p2.getPoRefNo())) {
					//System.out.println("############# po:"+isub.getPoRefNo());
					//System.out.println("p2.getTempMyDesc3().length()="+p2.getTempMyDesc3().length());
					if( !p2.getTempMyDesc3().contains(isub.getProjectCode())) {
						//System.out.println("############# "+p2.getTempMyDesc3());
						p2.setTempMyDesc3(p2.getTempMyDesc3()+isub.getProjectCode());
					}
				}
				p2List.add(p2);
			}
		}
		
		return p2List;
	}

	public static String getPreDocNo(String docNo, Date docDate) {
		// TODO Auto-generated method stub
		//docDate.
		return null;
	}
}
